package com.sanshow.charging.util;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadQueueSet;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.sanshow.charging.MainActivity;
import com.sanshow.charging.fragment.ImageFragment;
import com.sanshow.charging.fragment.VideoFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class VideoDownload {

    private static String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/sanshow/videos";
    private static ProgressDialog progressDialog = null;
    private static List<String> videoUrlPathList = new ArrayList<>();
    private static Context context = null;
    private static File[] existFiles = null;
    private static int fileCount = 0;

    // 多任务下载
    private static FileDownloadListener downloadListener;

    public static FileDownloadListener createLis() {
        return new FileDownloadSampleListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                if (task.getListener() != downloadListener) {
                    return;
                }
                Log.d("feifei", "pending taskId:" + task.getId() + ",fileName:" + task.getFilename() + ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes);

            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                if (task.getListener() != downloadListener) {
                    return;
                }
                Log.d("feifei", "progress taskId:" + task.getId() + ",fileName:" + task.getFilename() + ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes + ",speed:" + task.getSpeed());

                Long percent = Math.round(soFarBytes * 100.0 / totalBytes);
                Log.d("feifei", "process:" + soFarBytes * 1.0 / totalBytes);
                if (progressDialog == null) {
                    showProcessDialog();
                }
                progressDialog.setProgress(percent.intValue());
            }

            @Override
            protected void blockComplete(BaseDownloadTask task) {
                if (task.getListener() != downloadListener) {
                    return;
                }
                //Log.d("feifei", "blockComplete taskId:" + task.getId() + ",filePath:" + task.getPath() + ",fileName:" + task.getFilename() + ",speed:" + task.getSpeed() + ",isReuse:" + task.reuse());
                videoUrlPathList.remove(0);
                if (videoUrlPathList.size() > 0) {
                    progressDialog.dismiss();
                    progressDialog = null;
                    //progressDialog.setTitle("视频文件【" + videoUrlPathList.get(0) + "】下载中");
                    //progressDialog.setProgress(0);
                } else {
                    progressDialog.dismiss();
                    initVideos();
                }
            }

            @Override
            protected void completed(BaseDownloadTask task) {
                if (task.getListener() != downloadListener) {
                    return;
                }
                Log.d("feifei", "completed taskId:" + task.getId() + ",isReuse:" + task.reuse());
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                if (task.getListener() != downloadListener) {
                    return;
                }
                Log.d("feifei", "paused taskId:" + task.getId() + ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes);
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                if (task.getListener() != downloadListener) {
                    return;
                }
                Log.d("feifei", "error taskId:" + task.getId() + ",e:" + e.getLocalizedMessage());
            }

            @Override
            protected void warn(BaseDownloadTask task) {
                if (task.getListener() != downloadListener) {
                    return;
                }
                Log.d("feifei", "warn taskId:" + task.getId());
            }
        };
    }

    private static void initVideos() {
        MainActivity mainActivity = (MainActivity) context;
        deleteAllFiles(existFiles);
        mainActivity.showFragment(ImageFragment.newInstance());
        mainActivity.showFragment(VideoFragment.newInstance());
    }

    public static void downLoadVideo(Context activityContext, SimpleExoPlayer player, List<String> videoUrlPaths) {
        context = activityContext;
        player.pause();
        videoUrlPathList = videoUrlPaths;
        fileCount = videoUrlPaths.size();
        // 删除所有存在的视频文件
        //deleteAllFiles(new File(downloadPath));
        File dirFile = new File(downloadPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        existFiles = (new File(downloadPath)).listFiles();

        // 如果文件已存在，不下载
        String[] strUrlArr = videoUrlPaths.get(0).split("/");
        int len = strUrlArr.length;
        String strFileName = strUrlArr[len - 1];
        if (existFiles != null) {
            for (File f : existFiles) {
                if (f.exists()) { // 判断是否存在
                    try {
                        String fileName = f.getName();
                        if(fileName.equals(strFileName)){
                            return;
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }

        showProcessDialog();

        downloadListener = createLis();
        //(1) 创建 FileDownloadQueueSet
        final FileDownloadQueueSet queueSet = new FileDownloadQueueSet(downloadListener);

        //(2) 创建Task 队列
        final List<BaseDownloadTask> tasks = new ArrayList<>();
        // 并行执行该任务队列
        //queueSet.downloadTogether(tasks);
        // 如果你的任务不是一个List，可以考虑使用下面的方式，可读性更强
        for (int i = 0; i < videoUrlPaths.size(); i++) {
            BaseDownloadTask task = FileDownloader.getImpl().create(videoUrlPaths.get(i)).setPath(downloadPath, true);
            tasks.add(task);
        }

        //(3) 设置参数

        // 每个任务的进度 无回调
        queueSet.disableCallbackProgressTimes();
        // do not want each task's download progress's callback,we just consider which task will completed.

        queueSet.setCallbackProgressTimes(100);
        queueSet.setCallbackProgressMinInterval(100);
        //失败 重试次数
        queueSet.setAutoRetryTimes(3);

        //避免掉帧
        FileDownloader.enableAvoidDropFrame();

        //(4)串行下载
        queueSet.downloadSequentially(tasks);

        //(5)任务启动
        queueSet.start();
    }

    private static void showProcessDialog() {
        if (progressDialog != null) progressDialog = null;
        progressDialog = new ProgressDialog(context);
        progressDialog.setTitle("视频文件【" + videoUrlPathList.get(0).substring(videoUrlPathList.get(0).lastIndexOf("/") + 1) + "】下载中");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setProgress(0);
        progressDialog.show();
    }

    /**
     * private static void deleteAllFiles(File root) {
     * File files[] = root.listFiles();
     */
    private static void deleteAllFiles(File[] files) {
        if (files != null) {
            for (File f : files) {
                if (f.exists()) { // 判断是否存在
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
    /*private static void deleteAllFiles(File root) {
        File files[] = root.listFiles();
        if (files != null)
            for (File f : files) {
                if (f.isDirectory()) { // 判断是否为文件夹
                    deleteAllFiles(f);
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                } else {
                    if (f.exists()) { // 判断是否存在
                        deleteAllFiles(f);
                        try {
                            f.delete();
                        } catch (Exception e) {
                        }
                    }
                }
            }
    }*/

    // 获取目录下的所有文件夹
    public static List<String> getAllDataFileName() {
        List<String> fileList = new ArrayList<>();

        File file = new File(downloadPath);
        File[] tempList = file.listFiles();
        if (tempList != null && tempList.length > 0) {
            for (int i = 0; i < tempList.length; i++) {
                if (tempList[i].isFile()) {
                    System.out.println("文     件：" + tempList[i].getName());
                    // tempList[i].toString();// 路径
                    // tempList[i].getName();// 文件名
                    // 文件名
                    String fileName = downloadPath + "/" + tempList[i].getName();
                    fileList.add(fileName);
                }
            }
        }
        return fileList;
    }

}
